import { collide } from "@/utils/utils";
import { componentList, componentObj, currentComponent } from "./data";
import { DragBox } from "./types";

const getPosition = (item: DragBox) => {
  return {
    x: item.x,
    y: item.y,
    height: item.h,
    width: item.w
  };
};

export const moveUp = () => {
  componentList.value = componentList.value.filter((e) => {
    if (!currentComponent.value || e.id === currentComponent.value.id) return e;
    const rect1 = getPosition(e);
    const rect2 = getPosition(currentComponent.value);
    if (collide(rect1, rect2)) {
      const { z } = currentComponent.value;
      if (currentComponent.value.z < e.z) {
        currentComponent.value.z = e.z;
        e.z = z;
      }
    }
    return e;
  });
};

export const moveDown = () => {
  componentList.value = componentList.value.filter((e) => {
    if (!currentComponent.value || e.id === currentComponent.value.id) return e;
    const rect1 = getPosition(e);
    const rect2 = getPosition(currentComponent.value);
    if (collide(rect1, rect2)) {
      const { z } = currentComponent.value;
      if (currentComponent.value.z > e.z && currentComponent.value.z > 0) {
        currentComponent.value.z = e.z;
        e.z = z;
      }
    }
    return e;
  });
};

export const deleteComponent = () => {
  componentList.value = componentList.value.filter((e) => {
    return e.id !== currentComponent.value?.id;
  });
  currentComponent.value = {
    ...componentObj
  };
};
export const getMaxIndex = (): number => {
  if (componentList.value.length === 0) {
    return 1;
  }

  let maxZ = componentList.value?.[0].z;

  for (const box of componentList.value) {
    if (box.z > maxZ) {
      maxZ = box.z;
    }
  }

  return maxZ + 1;
};
